package com.bigscreen.controller;

import com.bd1904.common.CommonUtil;
import com.bigscreen.service.ShopRankService;
import org.springframework.stereotype.Controller;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

//websocket服务端 实现类
@ServerEndpoint("/web_socket/shop_ranking")
@Controller
public class RealTimeShopRankWebSocket {
    @OnOpen
    public void onOpen(){
        System.out.println("webSocket连接成功");
    }
    @OnClose
    public void onclose(){
        System.out.println("连接关闭");
    }

    //websocket 注入方式
    private static ShopRankService srService;
    public void setSrService(ShopRankService srService){
        RealTimeShopRankWebSocket.srService = srService;
    }
    @OnMessage
    public void onMessage(String message, Session session){
        //   top5/sec
        while(true){
            //求topN
            String topn = srService.shopRankTop(5,false);
            RemoteEndpoint.Basic basicRemote = session.getBasicRemote();
            try {
                basicRemote.sendText(topn);
            } catch (IOException e) {
                e.printStackTrace();
            }
            CommonUtil.sleep(1000);//每秒
        }

    }
}
